package com.example.authority.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.client.CustomsClient;
import com.example.authority.client.VideoClient;
import com.example.authority.service.HomeService;
import com.example.commons.common.Constant;
import com.example.commons.common.Result;
import com.example.commons.entity.Home;
import com.example.commons.entity.Map;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Tag(name = "首页表 前端控制器")
@RestController
@RequestMapping("/homepage")
public class HomeController {
    @Resource
    private HomeService homeService;

    /**
     * 新增首页内容
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result save(@RequestBody Home home) {
        home.setUid(StpUtil.getLoginIdAsLong()); // 设置当前用户ID
        home.setCreateTime(LocalDateTime.now());
        home.setState(1L); // 默认展示状态
        return Result.success(homeService.save(home));
    }

    /**
     * 修改首页内容
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id, @RequestBody Home home) {
        home.setId(id);
        home.setUpdateTime(LocalDateTime.now());
        return Result.success(homeService.updateById(home));
    }

    /**
     * 获取单个详情
     */
    @Operation(summary = "获取单个")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Long id) {
        return Result.success(homeService.getById(id));
    }

    /**
     * 分页查询
     */
    @Operation(summary = "分页显示")
    @GetMapping("/page")
    public Result findPage(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Long state,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Home> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(title)) {
            wrapper.like(Home::getTitle, title);
        }
        if (state != null) {
            wrapper.eq(Home::getState, state);
        }
        wrapper.orderByDesc(Home::getId);
        return Result.success(homeService.page(new Page<>(pageNum, pageSize), wrapper));
    }

    /**
     * 删除首页内容
     */
    @Operation(summary = "单个删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        return Result.success(homeService.removeById(id));
    }

    /**
     * 批量删除
     */
    @Operation(summary = "批量删除")
    @DeleteMapping("/batch/{ids}")
    @Transactional
    public Result deleteByIds(@PathVariable Long[] ids) {
        return Result.success(homeService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 导出数据
     */
    @Operation(summary = "批量导出")
    @GetMapping("/batch/export/{ids}")
    public void exportByIds(@PathVariable Long[] ids, HttpServletResponse response) throws IOException {
        List<Home> list = homeService.listByIds(Arrays.asList(ids));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("home导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Home.class).sheet("首页数据").doWrite(list);
    }

    @Operation(summary = "检查是否存在其他展示中的首页")
    @GetMapping("/exists")
    public Result checkActiveExists(@RequestParam(required = false) Long excludeId) {
        boolean exists = homeService.checkActiveExists(excludeId);
        return Result.success(exists);
    }
}